<?php


namespace app\app\controller;


use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Db;
use think\Validate;
use think\facade\Cache;
use DateTime;
use DateInterval;
use function Symfony\Component\String\b;

class Index extends Homebase
{
    protected $city_array;


    protected function initialize()
    {
        parent::initialize();
        $this->city_array = array('北京市', '上海市', '天津市', '重庆市');
        //    city  上海市
        //    longitude 117.120000
        //    latitude  36.650200
    }


    /**
     * 获取openid
     */
    public function wxLogin()
    {
        $code = $this->request->param("code");
        $appId = config('wechat.appID');
        $secret = config('wechat.AppSecret');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appId . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $res = lmcurl($url);
        msg(0, "成功", $res);
    }

    /**
     * 上传图片
     */
    // todo 转换成webp 看图片压缩
    public function upload_img()
    {
        $files = $this->request->file('file');//获取图片
        $info = $files->move(ROOT_PATH . 'public' . '/' . 'uploads');

        if ($info) {

            $logo = '/' . 'uploads' . '/' . $info->getSaveName();

            $datas = $info->getInfo();

            $img['path'] = $logo;

            $img['mime'] = $datas['type'];

            $img['name'] = $datas['name'];

            $img['size'] = $datas['size'];

            $img['sha1'] = $info->hash('sha1');

            $img['md5'] = $info->hash('md5');

            $img['driver'] = 'local';

            $img['create_time'] = time();

            $img['update_time'] = time();

            $img['status'] = 1;

            $img['ext'] = $info->getExtension();

            $id = Db::name('attachment')->insertGetId($img);
            //todo 关闭oss
//            if (config('is_oss') == 1) {
//                upload_local_file($id);
//            }
            $d = db('attachment')->where('id', $id)->find();
            if ($d['type'] == 1) {
                $d['path'] = conf("wechat", "url") . str_replace('\\', '/', $d['path']);
            } else {
                $d['path'] = conf("wechat", "url") . $d['path'];
            }
            msg(0, "获取成功", $d);

        } else {
            echo $files->getError();
        }
        //msg(0, "成功", $url);
    }

    /**
     * 获取手机号
     */
    public function getPhone()
    {
        try {
            $data = $this->request->param();
            $config = config('wechat.config');
            $app = Factory::miniProgram($config);
            $data = $app->phone_number->getUserPhoneNumber($data['code']);
            msg(0, '查询成功', $data);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    /**
     * @return void 保存用户信息
     */
    public function deuser()
    {
        $data = $this->request->param();

        $datas['openid'] = $data['openid'];

        $datas['reg_ip'] = $this->request->ip();

        $datas['mobile'] = $data['mobile'];

        $datas['nickname'] = $data['nickname'];

        $datas['avatarUrl'] = $data['avatarUrl'];

        if (isset($data['invite_id'])) {
            $datas['invite_id'] = $data['invite_id'];
        }

        $rules = [
            'openid' => 'require',
            'mobile' => 'require',
//            'nickname' => 'require',
//            'avatarUrl' => 'require',
        ];
        $message = [
            'openid.require' => 'openid必须',
            'mobile.require' => '手机必须',
//            'nickname.require' => '昵称必须',
//            'avatarUrl.require' => '头像必须',
        ];
        $validate = new Validate($rules, $message);
        $result = $validate->check($data);
        if (!$result) {
            msg(-1, '缺少信息', '');
        }
        $stmt = Db::name('member')->where('openid', $datas['openid'])->find();
        if ($stmt) {
            $datas['last_login_time'] = time();
            unset($datas['nickname']);
            unset($datas['avatarUrl']);
            Db::name('member')->where('openid', $datas['openid'])->update($datas);
            $member = Db::name('member')->where('openid', $datas['openid'])->find();
            if ($member['status'] == 0) {
                responseJson(-200, '用户已冻结', $member);
            }
            msg(0, '查询成功', $member);
        } else {
            $datas['create_time'] = time();
            $datas['status'] = 1;
            //一键默认登录 设置默认昵称 默认头像
            $datas['nickname'] = '用户' . rand(0000, 9999);
            $datas['avatarUrl'] = config('site.web_default_avatar');
            //邀请用户
            if (isset($data['invite_id'])) {

            }
            $user_id = Db::name('member')->insertGetId($datas);
            msg(0, '新建成功', $datas);
        }
    }

    /**
     * 获取各项配置
     */
    public function getConfigAdmin()
    {
        $data = $this->request->param();
        if ($data['set_name'] && isset($data['set_name'])) {
            msg(0, '查询完成', config('site.' . $data['set_name']));
        }
        msg(-1, '请输入查询内容', '');
    }

    //通过坐标获取位置信息
    public function getAddressByLocation()
    {
        $data = $this->request->param();
        //当前维度 经度 搜索关键字 页数 所在市
        $data_list = getAddressByLocation2($data['latitude'], $data['longitude']);
        $data_list = json_decode($data_list, true);
        if ($data_list['code'] == 0) {
            $data_list['data']['location']['lat'] = $data['latitude'];
            $data_list['data']['location']['lng'] = $data['longitude'];
            msg(0, '查询成功', $data_list['data']);
        } else {
            msg(-1, $data_list['data'], '');
        }
    }

    //通过市获取坐标
    public function getCityLocation()
    {
        $data = $this->request->param();
        //当前维度 经度 搜索关键字 页数 所在市
        $data_list = getLWByAddress($data['city']);
        $data_list = json_decode($data_list, true);
        if ($data_list['code'] == 0) {
            msg(0, '查询成功', $data_list['data']);
        } else {
            msg(-1, $data_list['data'], '');
        }
    }

    //获取评价标签
    public function getCommentLabList()
    {
        $result = Db::name('comment_label')
            ->where([
                'status' => 1,
                'is_del' => 0,
            ])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $result);
    }


    //获取天气
    public function getWeatherByCity()
    {
        $address = getCityByIP();
        $data = getWeatherByCity($address['city']);
        msg(0, '查询成功', $data);
    }

    /**
     * 获取banner图
     */
    public function getBanner()
    {
        $data = $this->request->param();
        //经纬度
//        if (in_array($data['city'], $this->city_array)) {
//            $return_data = Db::name('banner')
//                ->where(['status' => 1, 'is_del' => 0, 'province' => $data['city']])
//                ->order('sort desc')
//                ->select();
//        } else {
//            $return_data = Db::name('banner')
//                ->where(['status' => 1, 'is_del' => 0, 'city' => $data['city']])
//                ->order('sort desc')
//                ->select();
//        }
//        if (!$return_data) {
//            $return_data = Db::name('banner')
//                ->where(['status' => 1, 'is_del' => 0, 'province' => ''])
//                ->order('sort desc')
//                ->select();
//        }
        $return_data = Db::name('banner')
            ->where(['status' => 1, 'is_del' => 0,])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $return_data);
    }

    //获取陪诊服务列表
    public function getPzList()
    {
        $inputData = $this->request->param();
        $where = [['is_del', '=', 0], ['status', '=', 1], ['server_type', '=', 1]];
        if (isset($inputData['search']) && $inputData['search']) {
            $where[] = ['name', 'like', '%' . $inputData['search'] . '%'];
        }
        $data = Db::name('server')
            ->where($where)
            ->order('sort desc')->select();

        foreach ($data as $k => $v) {
            $data[$k]['tag'] = explode(',', $v['tag']);
        }
        msg(0, '查询成功', $data);
    }
    //获取护士服务列表
    public function getHsList()
    {
        $inputData = $this->request->param();
        $where = [['is_del', '=', 0], ['status', '=', 1], ['server_type', '=', 2]];
        if (isset($inputData['search']) && $inputData['search']) {
            $where[] = ['name', 'like', '%' . $inputData['search'] . '%'];
        }
        $data = Db::name('server')
            ->where($where)
            ->order('sort desc')->select();

        foreach ($data as $k => $v) {
            $data[$k]['tag'] = explode(',', $v['tag']);
        }
        msg(0, '查询成功', $data);
    }

    //获取导诊服务列表
    public function getDzList()
    {
        $data = Db::name('server2')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['tag'] = explode(',', $v['tag']);
        }
        msg(0, '查询成功', $data);
    }

    //获取接送服务列表
    public function getJsList()
    {
        $data = Db::name('server3')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['tag'] = explode(',', $v['tag']);
        }
        msg(0, '查询成功', $data);
    }

//    //首页推荐套餐
//    public function getPackageList()
//    {
//        $data = Db::name('package')
//            ->where(['is_del' => 0, 'status' => 1])
//            ->order('sort desc')->select();
//        msg(0, '查询成功', $data);
//    }

    //获取本市最近医院
    public function getHospitalRecently()
    {
        $data = $this->request->param();
        $where = array();
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        if (in_array($data['city'], $this->city_array)) {
            $where[] = ['province', '=', $data['city']];
        } else {
            $where[] = ['city', '=', $data['city']];
        }
        $return_data = Db::name('hospital')
            ->where($where)
            ->find();
        msg(0, '查询成功', $return_data);
    }

    //获取陪诊详情
    public function getServerDetail()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $server_id = $data['id'];
        $order_detail = Db::name('server')->find($server_id);
        $order_detail['sale_num'] = Db::name('server_order')->where([
            ['is_del', '=', 0],
            ['status', 'in', [2,3,4,7,8]],
            ['server_id','=',$server_id]
        ])->count();
        $order_detail['tag'] = explode(',', $order_detail['tag']);
        msg(0, '查询成功', $order_detail);
    }

    //获取陪诊服务评价顶部

    //获取陪诊评价列表

    //下单列表

    //获取当前位置医院列表
    public function getHospitalList()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        if (isset($data['search_name']) && $data['search_name']) {
            $where[] = ['name', 'like', '%' . $data['search_name'] . '%'];
        }
        if (in_array($city, $this->city_array)) {
            $where[] = ['province', '=', $data['city']];
        } else {
            $where[] = ['city', '=', $data['city']];
        }
        $return_data = Db::name('hospital')->where($where)->select();
        foreach ($return_data as $k => $v) {
            $return_data[$k]['distance'] = 560;
            $return_data[$k]['doctor_num'] = 12;
            $return_data[$k]['is_distance'] = 0;
        }
        $return_data[0]['is_distance'] = 1;
        msg(0, '查询成功', $return_data);
    }

    //获取医院科室列表
    public function getDepartment()
    {
        $data = $this->request->param();
        $hospital_id = $data['hospital_id'];
        $_list = Db::name('department')
            ->where(['is_del' => 0, 'hospital_id' => $hospital_id, 'pid' => 0])
            ->order('sort desc')
            ->select();
        foreach ($_list as $k => $v) {
            $_list[$k]['is_able'] = 1;
        }
        //  $_list2 = listToTree($_list, $pk = 'id', $pid = 'pid', $child = 'child');
        msg(0, '查询成功', $_list);
    }

    //获取科室列表2
    public function getDepartment2()
    {
        $data = $this->request->param();
        $_list = Db::name('department')
            ->where(['is_del' => 0, 'pid' => $data['id']])
            ->order('sort desc')
            ->select();
        foreach ($_list as $k => $v) {
            $_list[$k]['is_able'] = 1;
        }
        //  $_list2 = listToTree($_list, $pk = 'id', $pid = 'pid', $child = 'child');
        msg(0, '查询成功', $_list);
    }

    //获取导诊服务详情
    public function server2Detail()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];

        $order_detail = Db::name('server2')->find();
        $order_detail['tag'] = explode(',', $order_detail['tag']);
        msg(0, '查询成功', $order_detail);
    }

    //导诊服务评价顶部
    //导诊评价列表

    //支持导诊地区
    public function server2Area()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $city_list = Db::name('hospital')
            ->field('real_city,count(*) as num')
            ->group('real_city')
            ->where(['is_del' => 0, 'status' => 1])
            ->select();
        msg(0, '查询成功', $city_list);
    }

    //疾病列表
    public function getCbingList()
    {
        $data_list = Db::name('cbing')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $data_list);
    }

    //推荐医院城市导诊选择
    public function getHospital2()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $where[] = ['real_city', '=', $city];
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        if (isset($data['cbing_id']) && $data['cbing_id']) {
            //todo 关联疾病
        }
        $data_list = Db::name('hospital')
            ->order('sort desc')
            ->where($where)
            ->select();
        foreach ($data_list as $k => $v) {
            $data_list[$k]['distance'] = 560;
            $data_list[$k]['doctor_num'] = 12;
        }
        msg(0, '查询成功', $data_list);

    }

    //推荐医生城市/医院
    public function getDoctorList()
    {
        $data = $this->request->param();
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        if (isset($data['city']) && $data['city']) {
            $where[] = ['real_city', '=', $data['city']];
        }
        if (isset($data['hospital_id']) && $data['hospital_id']) {
            $where[] = ['hospita_id', '=', $data['hospital_id']];
        }
        if (isset($data['cbing_id']) && $data['cbing_id']) {
            //todo 关联疾病
        }

        $data_list = Db::name('doctor')->where($where)
            ->order('sort desc')
            ->select();
        foreach ($data_list as $k => $v) {
            $department_info = Db::name('department')->find($v['department_id']);
            $data_list[$k]['department'] = $department_info['name'];
        }
        msg(0, '查询成功', $data_list);
    }

    //医院详情
    public function hospItalDetail()
    {
        $data = $this->request->param();
        $return_data = Db::name('hospital')->find($data['id']);
        $return_data['distance'] = 560;
        $return_data['doctor_num'] = 12;
        msg(0, '查询成功', $return_data);
    }

    //医生详情
    public function doctorDetail()
    {
        $data = $this->request->param();
        $doctor_id = $data['id'];
        $doctor_info = Db::name('doctor')->find($doctor_id);
        $hospital_info = Db::name('hospital')->find($doctor_info['hospital_id']);
        $department = Db::name('department')->find($doctor_info['department_id']);
        $doctor_info['hospital'] = $hospital_info['name'];
        $doctor_info['hospital_level'] = explode(',', $hospital_info['tag']);
        $doctor_info['department'] = $department['name'];
        msg(0, '查询成功', $doctor_info);
    }

    //获取最近四天日期 并显示周几
    public function getData()
    {
        // 创建一个 DateTime 对象，表示当前日期
        $currentDate = new DateTime();
        // 创建一个数组来保存往后四天的日期和星期几
        $dates = [];
        // 循环四次，每次增加一天
        for ($i = -1; $i < 3; $i++) {
            // 克隆当前日期对象
            $date = clone $currentDate;

            // 增加 $i+1 天（因为 $i 是从 0 开始的）
            $date->add(new DateInterval('P' . ($i + 1) . 'D'));

            // 获取日期的字符串表示
            $dateString = $date->format('m-d');

            // 获取星期几，使用 'l' 格式化字符表示完整的星期名称
            $dayOfWeek = $date->format('w');
            $weekMap = [0 => '周日', 1 => '周一', 2 => '周二', 3 => '周三', 4 => '周四', 5 => '周五', 6 => '周六'];
            //            $weekDay = date('w');
            // 将日期和星期几添加到数组中
            $dates[] = ['date' => $dateString, 'dayOfWeek' => $weekMap[$dayOfWeek]];
        }
        msg(0, '查询成功', $dates);
    }

    //接送服务详情
    public function jsDetail()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];

        $order_detail = Db::name('server3')->find();
        $order_detail['tag'] = explode(',', $order_detail['tag']);
        msg(0, '查询成功', $order_detail);
    }
    //接送评价顶部
    //接送评价列表

    //获取积分商品类型
    public function getGoodsCate2()
    {
        $data_list = Db::name('goods_categoty')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $data_list);
    }

    //获取积分商品列表
    public function getGoodsList()
    {
        // 0陪诊 1医疗用品 2优惠卷
        $data = $this->request->param();
        $cate_id = $data['cate_id'];
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $where[] = ['goods_cate', '=', $cate_id];
        $data_list = Db::name('goods')
            ->where($where)
            ->order('sort desc')
            ->page($page, $length)
            ->select();
        if ($cate_id == 2) {
            foreach ($data_list as $k => $v) {
                $coupons_info = Db::name('coupons')->find($v['object_id']);
                $data_list[$k]['value'] = $coupons_info['value'];
                $data_list[$k]['min_amount'] = $coupons_info['min_amount'];
                $data_list[$k]['effect_day'] = $coupons_info['effect_day'];
                $data_list[$k]['desc'] = $coupons_info['desc'];
            }
        } else if ($cate_id == 0) {
            foreach ($data_list as $k => $v) {
                $server_info = Db::name('server')->find($v['object_id']);
                $data_list[$k]['name'] = $server_info['name'];
                $data_list[$k]['img'] = $server_info['bc_img'];;
            }
        }
        msg(0, '查询成功', $data_list);
    }

    //获取商品详情
    public function getGoodsDetail()
    {
        //1优惠卷 2陪诊服务 3医疗用品
        //0陪诊 1医疗用品 2优惠卷
        $data = $this->request->param();
        $goods_id = $data['id'];
        $data_detail = Db::name('goods')->find($goods_id);
        if ($data_detail['goods_cate'] == 0) {
            $data_detail = Db::name('server')->find($data_detail['object_id']);
            $c_info = Db::name('goods')->find($goods_id);
            $data_detail['points'] = $c_info['points'];
            $data_detail['tag'] = explode(',', $data_detail['tag']);
            $data_detail['id'] = $goods_id;
        }
        if ($data_detail['goods_cate'] == 2) {
            $data_detail = Db::name('coupons')->find($data_detail['object_id']);
            $c_info = Db::name('goods')->find($goods_id);
            $data_detail['points'] = $c_info['points'];
            $data_detail['id'] = $goods_id;
        }
        msg(0, '查询成功', $data_detail);
    }

    //获取陪诊 护士列表
    public function getPzPeopleList()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        if (isset($data['type']) && $data['type']) {
            $where[] = ['type', '=', $data['type']];
        }
        if (isset($data['name']) && $data['name']) {
            $where[] = ['name', 'like', '%' . $data['name'] . '%'];
        }
        $pz_list = Db::name('pz')->where([
//            ['province|city', '=', $city],
            ['is_del', '=', 0],
            ['is_online', '=', 1],
            ['status', '=', 1],
        ])->where($where)
            ->order('order_num desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['comment_rate'] = $this->haopinRate($item['id']);
                $level_info = Db::name('pz_level')->find($item['pz_level_id']);
                $item['level_info'] = $level_info;
                return $item;
            });
        msg(0, '查询成功', $pz_list);
    }

    public function haopinRate($pz_id){
        $zong=Db::name('comment')->where([
            ['pz_id','=',$pz_id],
            ['is_del','=',0],
        ])->count();
        if ($zong){
            $hao=Db::name('comment')->where([
                ['pz_id','=',$pz_id],
                ['is_del','=',0],
                ['score','>',3],
            ])->count();
        return $hao/$zong*100;
        }
        return 100;
    }

    //获取陪诊护士详情
    public function getPzDetail()
    {
        $data = $this->request->param();
        $pz_info = Db::name('pz')->find($data['id']);
        $pz_info['hao_rate'] = $this->haopinRate($data['id']);
        $pz_level = Db::name('pz_level')->find($pz_info['pz_level_id']);
        $pz_info['pz_level'] = $pz_level;
        $q_img = Db::name('qualification')->where([
            'pz_id' => $data['id']
        ])->order('sort')->select();
        $data['info'] = $pz_info;
        foreach ($q_img as $k=>$v){
            $data['q_img'][]=$v['img'];
        }
        msg(0, '查询成功', $data);
    }

    //获取新人卡
    public function getPackageList()
    {
        $data = $this->request->param();
        $PackageList = Db::name('package')
            ->where(['is_del' => 0, 'status' => 1])
            ->where('id', '=', 3)->find();
        $server_count = Db::name('package_server')->where([
            'package_id' => $PackageList['id']
        ])->sum('num');
        $icon_img = config('site.pz_card');
        $PackageList['server_count'] = $server_count;
        $PackageList['icon_img'] = $icon_img[0];
        msg(0, '查询成功', $PackageList);
    }

    //获取套餐列表
    public function getPackageList2()
    {
        $data = $this->request->param();
        $PackageList = Db::name('package')
            ->where(['is_del' => 0, 'status' => 1])
            ->where('id', '<>', 3)
            ->order('sort desc')->select();
        $icon_img = config('site.pz_card');
        foreach ($PackageList as $k => $v) {
            $server_count = Db::name('package_server')->where([
                'package_id' => $v['id']
            ])->sum('num');
            $PackageList[$k]['icon_img'] = $icon_img[$k + 1];
            $PackageList[$k]['server_name'] = '半天陪诊';
        }
        msg(0, '查询成功', $PackageList);
    }


    //获取套餐详情
    public function getPackageDetail()
    {
        $data = $this->request->param();
        $package_id = $data['id'];
        $package_data = Db::name('package')->find($package_id);
        $package_server = Db::name('package_server')->where([['num', '>', 0], ['package_id', '=', $package_id]])->select();
        $package_data['server_count'] = count($package_server);
        foreach ($package_server as $k => $v) {
            $server_info = Db::name('server')->find($v['server_id']);
            $server_info['tag'] = explode(',', $server_info['tag']);
            $package_server[$k]['server_info'] = $server_info;
        }
        $return_data['package_data'] = $package_data;
        $return_data['package_server'] = $package_server;
        msg(0, '查询成功', $return_data);
    }

    //首页接口 1
    public function cIndex()
    {
        //会员数量 订单数量 服务数量 待审核提现 待转账确认
        $a = Db::name('member')->where([['openid', '<>', 0]])->count();
        $b = Db::name('server_order')->where([
            ['status', 'in', [2, 3, 4, 7, 8]],
        ])->count();
        $c = Db::name('server')->where([['is_del', '=', 0]])->count();

        $d = Db::name('member_finance')->where([['status', '=', 0]])->count();
        $e = Db::name('member_finance')->where([
            ['status', '=', 1],
            ['is_kuan', '=', 0]
        ])->count();
        //陪诊师数量
        $pz_num = Db::name('pz')->where([
            ['status', 'in', [1, 2]],
            ['type', '=', 1],
            ['is_del', '=', 0]
        ])->count();
        $nurse_num = Db::name('pz')->where([
            ['status', 'in', [1, 2]],
            ['type', '=', 2],
            ['is_del', '=', 0]
        ])->count();
        $data['a'] = $a;
        $data['b'] = $b;
        $data['c'] = $c;
        $data['d'] = $pz_num;
        $data['e'] = $nurse_num;
        msg(0, '查询更改', $data);
    }
    //首页接口 2
    //1待支付2带指派3服务中4已完成5已取消6已退款7已指派8已评价'
    public function cIndex2()
    {
        $a = Db::name('server_order')->where([
            ['status', 'in', [2, 3, 4, 7, 8]]
        ])->sum('pay_money');
        $b = Db::name('package_order')->where([
            ['status', 'in', [2]]
        ])->sum('pay_money');
        $member_ids = Db::name('pz')->where([
            ['status', 'in', [1, 2]],
        ])->column('member_id');
        $c1 = Db::name('member')->where('id', 'in', $member_ids)->sum('account');
        $c2 = Db::name('fx')->sum('money');
        $c = round($c1 + $c2,2);
        $d = Db::name('member_finance')->where([
            ['type', 'in', [3, 4]],
            ['is_count', '=', 2],
            ['is_kuan', '=', 0]
        ])->sum('money');
        $e = Db::name('member_finance')->where([
            ['type', 'in', [3, 4]],
            ['is_count', '=', 2],
            ['is_kuan', '=', 1]
        ])->sum('money');
        $data['a'] = $a;
        $data['b'] = $b;
        $data['c'] = $c;
        $data['d'] = $d;
        $data['e'] = $e;
        msg(0, '查询更改', $data);
    }

    //服务订单数量 1待支付2带指派3服务中4已完成5已取消6已退款7已指派8已评价
    public function getPie()
    {
        $return_data = array();
        $server_info = Db::name('server')->where([
            'is_del' => 0
        ])->select();
        foreach ($server_info as $k => $v) {

            $num = Db::name('server_order')->where([
                ['status', 'in', [2, 3, 4, 7, 8]],
                ['server_id', '=', $v['id']]
            ])->count();
//            if ($num>0){
            $return_data[$k]['name'] = $v['name'];
            $return_data[$k]['value'] = $num;
//            }

        }
        msg(0, '查询更改', $return_data);
    }

    public function getbar()
    {
        $pz_list = Db::name('pz')
            ->where([
                ['status', 'in', [1, 2]],
                ['is_del', 'in', [0]],
            ])
            ->order('order_num desc')
            ->limit(10)->select();
        $data1 = array();
        $data2 = array();
        foreach ($pz_list as $k => $v) {
            $data1[] = $v['name'];
            $data2[] = $v['order_num'];
        }
        $return_data['data1'] = $data1;
        $return_data['data2'] = $data2;
        msg(0, '查询更改', $return_data);
    }

    //banner修改
    //陪诊订单 定时完成 订单状态 1待支付2带指派3服务中4已完成5已取消6已退款7已指派8已评价
    public function getOrderPay()
    {
        Db::startTrans();
        try {
            $limit = 60;
            $page = Cache::get('getAccount_page');
            if (!$page) {
                $page = 1;
                Cache::set('getAccount_page', $page);
            }
            $order_where = [
                ['status', '=', 1],//1待支付
            ];
            $order_list = Db::name('server_order')
                ->page($page, $limit)
                ->where($order_where)
                ->order('create_time desc')
                ->select();

            if (!$order_list) {
                $page = 1;
                Cache::set('getAccount_page', $page);
                msg(100, '订单为空', '');
            }
            Cache::set('getAccount_page', ++$page);
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            foreach ($order_list as $k => $item) {
                $res = $app->order->queryByOutTradeNumber($item['order_no']);
                if ($res['trade_state'] == "SUCCESS") {
                    serverPaySuccess($item);
                }
            }
            Db::commit();
//            msg(0, '查询成功', $order_list);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //陪诊卡定时 完成
    public function getPackagePay()
    {
        Db::startTrans();
        try {
            $limit = 60;
            $page = Cache::get('getAccount_page2');
            if (!$page) {
                $page = 1;
                Cache::set('getAccount_page2', $page);
            }
            $order_where = [
                ['status', '=', 1],//1待支付
            ];
            $order_list = Db::name('package_order')
                ->page($page, $limit)
                ->where($order_where)
                ->order('create_time desc')
                ->select();
            if (!$order_list) {
                $page = 1;
                Cache::set('getAccount_page2', $page);
                msg(100, '陪诊卡订单为空', '');
            }
            Cache::set('getAccount_page2', ++$page);
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            foreach ($order_list as $k => $item) {
                $res = $app->order->queryByOutTradeNumber($item['order_no']);
                if ($res['trade_state'] == "SUCCESS") {
                    if ($item['status'] == 1) {
                        packageBack($item, $item['member_id']);
                    }
                }
            }
            Db::commit();
//            msg(0, '查询成功', $order_list);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }
    //定时判断陪诊卡过期退款
    public function getPackageOut()
    {
        Db::startTrans();
        try {
            $limit = 60;
            $page = Cache::get('getAccount_pagec2');
            if (!$page) {
                $page = 1;
                Cache::set('getAccount_pagec2', $page);
            }
            $member_package_where=array(
                ['end_time','<',time()],
                ['order_no','>',0],
                ['is_del','=',0]
            );
            $member_package_list = Db::name('member_package')
                ->page($page, $limit)
                ->where($member_package_where)
                ->order('create_time desc')
                ->select();
            if (!$member_package_list) {
                $page = 1;
                Cache::set('getAccount_pagec2', $page);
                msg(100, '没有过期', '');
            }
            Cache::set('getAccount_pagec2', ++$page);
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            foreach ($member_package_list as $k => $item) {
                $member_package_server_info=Db::name('member_package_server')->where([
                    ['server_num','>',0],
                    ['mp_id','=',$item['id']]
                ])->find();
                if ($member_package_server_info['server_num']==$member_package_server_info['num']){
                    $package_order_info=Db::name('package_order')
                        ->where('order_no','=',$item['order_no'])
                        ->find();
                    $result = $app->refund->byOutTradeNumber($item['order_no'], $item['order_no'], $package_order_info['pay_money']*100, $package_order_info['pay_money']*100,
                        [
                        // 可在此处传入其他参数，详细参数见微信支付文档
                        'refund_desc' => '陪诊卡退款',
                    ]);
                    tuikuanPackOrder($package_order_info,$package_order_info['id']);
//                    Db::name('member_package')->where(['id'=>$item['id']])->update([
//                        'is_del'=>1
//                    ]);
                }
            }
            Db::commit();
            msg(0, '查询成功', $result);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //定时任务取消
    public function orderTime()
    {
        Db::startTrans();
        try {
            $order_list = Db::name('server_order')->where([
                'is_del' => 0,
                'status' => 1
            ])->select();
            foreach ($order_list as $k => $v) {
                //超过15分钟未支付为失效
                $a = time() - ($v['create_time'] + 15 * 60);
                if ($a >= 0) {
                    $update = array(
                        'id' => $v['id'],
                        'status' => 5,
                        'cancal_time' => time()
                    );
                    Db::name('server_order')->update($update);
                }
            }
            Db::commit();
            msg(0, '定时任务取消', date('Y-m-d H:i:s'));
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //定时任务 陪诊卡订单定时取消
    public function order2Time()
    {
        Db::startTrans();
        try {
            Db::commit();
            $order_list = Db::name('package_order')->where([
                'status' => 1
            ])->select();
            foreach ($order_list as $k => $v) {
                $a = time() - ($v['create_time'] + 15 * 60);
                if ($a >= 0) {
                    $update = array(
                        'id' => $v['id'],
                        'status' => 4,
                        'cancal_time' => time()
                    );
                    Db::name('package_order')->update($update);
                }
            }
            msg(0, '陪诊卡订单定时取消', date('Y-m-d H:i:s'));
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }
    //定时任务 订单完成
    public function finishOrder(){
        $server_order=Db::name('server_order')->where(['status'=>3])->select();
        foreach ($server_order as $k=>$v){
            if (!isTimestampToday($v['start_time'])){
                $ServerOrderInfo = Db::name('server_order')
                    ->where([
                        'id' => $v['id'],
                        'is_del' => 0
                    ])->find();
                $update_data = array(
                    'status' => 4,
                    'id' => $v['id'],
                    'end_time' => time()
                );
                //陪诊加钱
                $pz_info = Db::name('pz')->find($ServerOrderInfo['pz_id']);
                Db::name('pz')->where('id','=',$ServerOrderInfo['pz_id'])
                    ->setInc('order_num');
                addMoney($ServerOrderInfo,
                    1,
                    $pz_info['member_id'],
                    $ServerOrderInfo['get_money'],
                    '服务订单：' . $ServerOrderInfo['order_no'],
                    1
                );
                //分销
                addFxMoney($ServerOrderInfo, 1);
                Db::name('server_order')->update($update_data);
                Db::name('server')->where([
                    'id'=>$ServerOrderInfo['server_id']
                ])->setInc('sale_num');
            }
        }
        msg(0, '订单完成', $server_order);
    }

    public function tuiOnec()
    {
        $data = $this->request->param();
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($data['order_no'], $data['order_no'], 1, 1, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '订单退款',
        ]);
        msg(0, '退款完成', $result);
    }

    //获取陪诊员的可接项目
    public function getPzListbyPz()
    {
        $inputData = $this->request->param();

        $where = [['is_del', '=', 0], ['status', '=', 1]];
        if (isset($inputData['search']) && $inputData['search']) {
            $where[] = ['name', 'like', '%' . $inputData['search'] . '%'];
        }
        if ($inputData['type'] == 2) {
            $where[] = ['server_type', '=', 2];
        }
        $data = Db::name('server')
            ->where($where)
            ->order('sort desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['is_able'] = 0;
            $data[$k]['tag'] = explode(',', $v['tag']);
        }
        msg(0, '查询成功', $data);
    }

    //消息发送通知
    //服务端消息
    public function onMessageSend1()
    {
        $data = $this->request->param();
        try {
            $config = [
                'app_id' => config('wechat.appID'),
                'secret' => config('wechat.AppSecret'),
            ];
            $order_info = Db::name('server_order')->where('order_no', $data['order_no'])->find();
            if (!$order_info){
                msg(-2, '订单不存在', '');
            }
            $server_info=Db::name('server')->find($order_info['server_id']);
            if (!$order_info['pz_id']) {
                $app = Factory::miniProgram($config);
                $send_data= [
                    'template_id' => 'MfE3FaMjZ_2QGhPgdwKF2g5mFsgiEZ6vxss4SI92PR0', // 所需下发的订阅模板id
//                    'touser' => $bindMember['openid'],     // 接收者（用户）的 openid
                    'page' => 'pages/manage/manageOrder/manageOrder',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [
                        //商品名称
                        'thing1' => [
                            'value' => $server_info['name'],
                        ],
                        'character_string4' => [
                            'value' => $order_info['order_no'],
                        ],
                        'date2' => [
                            'value' =>date('Y-m-d H:i:s',$order_info['create_time']),
                        ],
                    ],
                ];
                $manager_list=Db::name('member')->where([['is_manage','=',1]])->select();
                foreach ($manager_list as $k=>$v){
                    $send_data['touser']=$v['openid'];
                    $data = $app->subscribe_message->send($send_data);
                }
                msg(0, '发送完成', $data);
            }
            msg(0, '发送完成2', $data);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), '');
        }
    }

    //陪诊师开始服务 给用户发送消息
    public function onMessageSend2()
    {
        $data = $this->request->param();
        try {
            $config = [
                'app_id' => config('wechat.appID'),
                'secret' => config('wechat.AppSecret'),
            ];
            $order_info = Db::name('server_order')->where('order_no', $data['order_no'])->find();
            if (!$order_info){
                msg(-2, '订单不存在', '');
            }

//            if ($order_info['pz_id']) {
                $member_info=Db::name('member')->find($order_info['member_id']);
                $pz_info=Db::name('pz')->find($order_info['pz_id']);
                $app = Factory::miniProgram($config);

                $send_data = [
                    'template_id' => 'Tj_MwaT78Rvr6Kr2uFCrX6JjWXfJLIkK54S2nGMNrCA', // 所需下发的订阅模板id
                    'touser' => $member_info['openid'],     // 接收者（用户）的 openid
                    'page' => 'pages/order/order?id=4',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [
                        //商品名称
                        'thing1' => [
                            'value' => $pz_info['name'],
                        ],
                        'phone_number2' => [
                            'value' => $pz_info['phone'],
                        ],
                    ],
                ];
                $data = $app->subscribe_message->send($send_data);
//                msg(0, '发送完成2', $data);
//            }
            msg(0, '发送完成', $data);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), '');
        }
    }

    //管理员分配 给陪诊师护士发送消息
    public function onMessageSend3()
    {
        $data = $this->request->param();
        try {
            $config = [
                'app_id' => config('wechat.appID'),
                'secret' => config('wechat.AppSecret'),
            ];
            $order_info = Db::name('server_order')->where('order_no', $data['order_no'])->find();
            if (!$order_info){
                msg(-2, '订单不存在', '');
            }
            if ($order_info['pz_id']) {
                $pz_info=Db::name('pz')->find($order_info['pz_id']);
                $member_info=Db::name('member')->find($pz_info['member_id']);
                $server_info=Db::name('server')->find($order_info['server_id']);
                $app = Factory::miniProgram($config);
                $send_data = [
                    'template_id' => '9_iZdYFwXCA1sg-1U0eBDiplDRdxDMaI_ZUTqU_zIyE', // 所需下发的订阅模板id
                    'touser' => $member_info['openid'],     // 接收者（用户）的 openid
                    'page' => 'pages/PatientEscort/Hall/Hall',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [
                        //订单号
                        'character_string1' => [
                            'value' => $data['order_no'],
                        ],
                        //项目名称
                        'thing24' => [
                            'value' => $server_info['name'],
                        ],
                        //创建时间
                        'time27' => [
                            'value' =>date('Y-m-d H:i:s',$order_info['time']),
                        ],
                    ],
                ];
                $data = $app->subscribe_message->send($send_data);
            }
            msg(0, '发送完成', '');
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), '');
        }
    }
    public function initData(){
        //清空陪诊员余额
        Db::name('member_id')->where('id','<>',-1)->update(
            [
                'account'=>0
            ]
        );
        Db::name('fx')->where('status','<>',-1)->update(
            [
                'money'=>0
            ]
        );
        Db::name('member_finance')->delete();
        Db::name('server_order')->delete();
        Db::name('package_order')->delete();
        Db::name('member_package')->delete();
        Db::name('member_package_server')->delete();
    }
    //会员标识
    public function getM2(){
        $data['title']='尊享会员';
        $data['desc']='陪诊项目专属优惠';
        $data['bg']=config('site.vip_bg');
        $data['icon']=config('site.icon');
        msg(0, '查询成功', $data);
    }
    //开通集团会员标识
    public function getM3(){
        $data['title']='集团会员';
        $data['desc']='陪诊项目专属优惠';
        $data['icon']=config('site.jijh_icon');
        $data['bg']=config('site.jijh_bg');
        msg(0, '查询成功', $data);
    }

    //会员卡权益列表
    public function vipDetail2()
    {
        $data = $this->request->param();
        $desc_list = Db::name('vip_desc')
            ->where(['vip_id' => $data['id']])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $desc_list);
    }
}
